from django import http
from django.core.cache import cache

from django.shortcuts import render
from django.views import View

from meidou_mall.apps.areas.models import Area
from meidou_mall.utils.response_code import RET


# Create your views here.
class AreaView(View):

    def get(self, request):
        area_id = request.GET.get('area_id')
        if not area_id:
            province_list = cache.get('province_list')
            if province_list:
                data_dict = {
                    "code": RET.OK,
                    "province_list": province_list,
                }

                return http.JsonResponse(data_dict)
            else:
                provinces = Area.objects.filter(parent=None).all()
                province_list = []
                for province in provinces:
                    item_dict = {
                        "id": province.id,
                        "name": province.name,
                    }

                    province_list.append(item_dict)

                data_dict = {
                    "code": RET.OK,
                    "province_list": province_list,
                }

                cache.set('province_list', province_list)
                return http.JsonResponse(data_dict)
        else:
            subs = cache.get('subs_{}'.format(area_id))
            if subs:
                data_dict = {
                    "code": RET.OK,
                    "sub_data": {
                        "subs": subs
                    }
                }

                return http.JsonResponse(data_dict)
            else:
                cities = Area.objects.filter(parent=area_id).all()
                subs = []
                for city in cities:
                    city_dict = {
                        "id": city.id,
                        "name": city.name,
                    }

                    subs.append(city_dict)

                data_dict = {
                    "code": RET.OK,
                    "sub_data": {
                        "subs": subs
                    }
                }

                cache.set('subs_{}'.format(area_id), subs)

                return http.JsonResponse(data_dict)



















